package com.dap.dubbo.rpc.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.dap.dubbo.rpc.config.RedisConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Activate(group ={ Constants.PROVIDER})
public class ValidationProviderFilter implements Filter {
    public static final String DUBBO_APPLICATION_KEY = "Application:";
    private static final Logger LOGGER = LoggerFactory.getLogger(ValidationProviderFilter.class);
    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        Jedis jedis = RedisConfig.getJedis();
        String application = invoker.getUrl().getParameter(Constants.APPLICATION_KEY);
        String ipBacks = jedis.get(DUBBO_APPLICATION_KEY+ application+":ipBackList" );
        List<String> ipBackList=new ArrayList<>();
        if(ipBacks!=null){
            if(!"".equals(DUBBO_APPLICATION_KEY+application+":ipBackList")){
             ipBackList= Arrays.asList(ipBacks.split(","));
            }
        }else{
            jedis.set(DUBBO_APPLICATION_KEY+application+":ipBackList","");
        }
        if (jedis != null) {
            jedis.close();
        }
        String clientIp = RpcContext.getContext().getRemoteHost();//客户端ip
        LOGGER.debug("访问ip为{}", clientIp);
        if (!ipBackList.contains(clientIp) || ipBackList==null || ipBackList.size()==0 ) {
            return invoker.invoke(invocation);
        } else {
            return new RpcResult(new Exception("ip地址："
                    + clientIp + "没有访问权限"));
        }
    }
}
